const path = require("path")
const { spawn } = require("child_process")
const webpackPath = require("./webpack.path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
    entry: path.join(webpackPath.srcRendererPath, "index.tsx"),
    output: {
        filename: '[name].renderer.js',
        path: path.join(webpackPath.rootPath, 'dist'),
        clean: true,
        publicPath: '/'
    },
    mode: 'development',
    devtool: 'inline-source-map',
    target: ['web', 'electron-renderer'],
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(webpackPath.rootPath, "public", "index.html")
        }),
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx|ts|tsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
                    },
                },
            },
            {
                test: /\.(sa|sc|c)ss$/i,
                use: [{
                    loader: 'style-loader'
                }, {
                    loader: 'css-loader',
                    options: {
                        modules: {
                            localIdentName: "[local]--[hash:base64:6]",
                        }
                    }
                }],
                exclude: [path.resolve(__dirname, '..', 'node_modules')]
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
            }

        ],
    },
    resolve: {
        extensions: ['.js', '.tsx', '.ts', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, '..', 'src')
        }
    },

    devServer: {
        port: 3000,
        open: false,
        historyApiFallback: true,
        static: webpackPath.distPath,
        proxy: {
            '/api': {
                target: 'https://www.wanandroid.com',
                secure: false,
                changeOrigin: true,
                pathRewrite: { '^/api': '' },
            },
        },
        setupMiddlewares: (middlewares, devServer) => {

            console.log('Starting Main Process...');

            spawn('npm', ['run', 'start:nodemon'], {
                shell: true,
                stdio: 'inherit',
            })
                .on('close', (code) => {
                    process.exit(code);
                })
                .on('error', (spawnError) => console.error(spawnError));
            return middlewares
        }
    }
}